package com.ly.mpayment.rest.up.fulu;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("fulu")
public class FuLuRest {
    Logger logger = Logger.getLogger(FuLuRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;



    @Path("callBack")
    @POST
    public String callBack(@RequestBody String body) {
        logger.info("fulu_callback:"+body);
        if(StringUtils.isBlank(body)){
            return "success";
        }
        //订单状态： （success：成功，processing：处理中，failed：失败，untreated：未处理）
        JSONObject data = JSONObject.parseObject(body);
        UpOrder order = upOrderService.findById(data.getString("customer_order_no"));
        if (order != null && data.getString("order_status").equals("success") && order.getStatus() == Config.status[0]) {
            order.setRemark(StringUtils.isBlank(data.getString("operator_serial_number")) ? data.getString("order_status") : data.getString("operator_serial_number"));
            RechargeRest.successUpOrder.add(order);
            return "success";
        } else if (order != null && order.getStatus() == Config.status[0] && data.getString("order_status").equals("failed")) {
            order.setRemark(data.getString("order_status"));
            RechargeRest.failtUpOrder.add(order);
            return "success";
        } else {
            this.upOrderService.addOrderMsg(order,data.getString("order_status"));
            logger.info("fulu_not_found_order:" + data.getString("order_status") + "," + (order == null ? "" : order.getUpphonenum()));
        }
        return "success";
    }


    public void commitOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = getPublicParam(order,shop);
        data.put("method", "fulu.order.mobile.add");
        JSONObject biz_content = new JSONObject();
        biz_content.put("charge_phone",order.getUpphonenum());
        biz_content.put("charge_value",order.getUpShopPro().getUpfacevalue());
        biz_content.put("customer_order_no",order.getUporderuuid());
        data.put("biz_content",biz_content.toString());
        char[] c = JSONObject.toJSONString(data, SerializerFeature.WriteMapNullValue).toCharArray();
        Arrays.sort(c);
        data.put("sign", MD5.md5( new String(c) + shop.getUpkey()));
        String result = HttpClient.post(shop.getOrderCommitAddress(),data.toString());
        logger.info("commitOrder_fulu:" + result + ":" + shop.getOrderCommitAddress().concat("?").concat(data.toString()));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                //订单状态： （success：成功，processing：处理中，failed：失败，untreated：未处理）
                if (json.containsKey("code") && json.getString("code").equals("0")
                && json.getJSONObject("result").getString("order_state").equals("untreated")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getJSONObject("result").getString("order_id"),json.containsKey("message") ?
                            json.getString("message") : "");
                } else if (json.containsKey("code") && errorCode.contains(json.getString("code"))){
                    order.setRemark(json.getString("message"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.updateUpOrderArtificial(order, "",json.getString("message"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","人工");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("1000");
        add("1001");
        add("1002");
        add("1003");
        add("1004");
        add("1005");
        add("1006");
        add("1007");
        add("1008");
        add("1009");
        add("1010");
        add("1011");
        add("1012");
        add("1013");
        add("1014");
        add("1015");
        add("1016");
        add("1017");
        add("1018");
        add("1019");
        add("2002");
        add("2003");
        add("2004");
        add("3001");
        add("3002");
        add("3003");
        add("3004");
        add("3005");
        add("4000");
        add("4002");
        add("4003");
        add("4004");
        add("4005");
        add("4010");
        add("5001");
    }};


    /**
     * 公共参数
     * @param order
     * @param shop
     * @return
     */
    private JSONObject getPublicParam(UpOrder order, UpShopInfo shop){
        JSONObject data = new JSONObject();
        data.put("app_key",shop.getAppId());
        data.put("timestamp", DateUtils.getNowDateYMDHMS());
        data.put("version","2.0");
        data.put("format","json");
        data.put("charset","utf-8");
        data.put("sign_type","md5");
        data.put("app_auth_token","");
        return data;
    }

    /**
     * 订单查询
     *
     * @param order
     * @param shop
     */
    public void queryOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = getPublicParam(order,shop);
        data.put("method", "fulu.order.info.get");
        JSONObject biz_content = new JSONObject();
        biz_content.put("customer_order_no",order.getUporderuuid());
        data.put("biz_content",biz_content.toString());
        char[] c = JSONObject.toJSONString(data, SerializerFeature.WriteMapNullValue).toCharArray();
        Arrays.sort(c);
        data.put("sign", MD5.md5( new String(c) + shop.getUpkey()));

        String result = HttpClient.post(shop.getOrderStatusAddress(),data.toString());
        logger.info("fuluqueryOrder:" + shop.getOrderStatusAddress()+ ":" + result+","+data);
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("code") && json.getString("code").equals("0")) {
                JSONObject item = json.getJSONObject("result");
                UpOrder upOrder = upOrderService.findById(item.getString("customer_order_no"));
                if (upOrder != null && item.getString("order_state").equals("success") && order.getStatus() == Config.status[0]) {
                    upOrder.setRemark( item.containsKey("operator_serial_number") ? item.getString("operator_serial_number") :
                            json.getString("message"));
                    RechargeRest.successUpOrder.add(upOrder);
                } else if (upOrder != null && order.getStatus() == Config.status[0] && item.getString("order_state").equals("failed") ) {
                    upOrder.setRemark(json.getString("message"));
                    RechargeRest.failtUpOrder.add(upOrder);
                } else {
                    this.upOrderService.addOrderMsg(order,json.getString("message"));
                    logger.info("fulu_not_found_order:" + upOrder.getUpphonenum());
                }
            } else {
                logger.info("fulu_not_found_order:" + order.getUpphonenum());
            }
        }
    }

}
